<template>
    <div class="nav-box">
        <el-menu :default-active="state.activeIndex" class="hp100" @select="handleSelect">
            <el-menu-item index="base">基础设置</el-menu-item>
            <el-menu-item index="net">网络设置</el-menu-item>
        </el-menu>
    </div>
    <div class="content-box">
        <div class="main">
            <el-form label-width="130" ref="refForm" :rules="state.rules" :model="state.formData">
                <template v-if="state.activeIndex == 'base'">
                    <el-form-item label="用户ID" prop="user_id">
                        <el-input type="text" v-model="state.formData.user_id" placeholder="请输入"/>
                    </el-form-item>
                    <el-form-item label="信令服务器地址" prop="server_url">
                        <el-input type="text" v-model="state.formData.server_url" placeholder="请输入"/>
                    </el-form-item>
                </template>
                <template v-if="state.activeIndex == 'net'">
                    <el-form-item label="代理" prop="proxy_url">
                        <el-input type="text" v-model="state.formData.proxy_url" placeholder="请输入"/>
                    </el-form-item>
                </template>

                <el-form-item>
                    <el-button type="primary" @click="saveForm()">保存</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {getSettingApi, settingEditApi} from "../../api/api";
import {ElMessage, ElMessageBox} from "element-plus";

const refForm = ref();
const defaultForm = {
    user_id: '',
    server_url: "http://127.0.0.1:8892",
    proxy_url: "",
};

const state = reactive({
    activeIndex: 'base',
    formData: {...defaultForm},
    rules: {
        user_id: [{required: true, message: '必填项', trigger: 'blur'}],
        server_url: [{required: true, message: '必填项', trigger: 'blur'}],
    },
});
const handleSelect = (key, keyPath) => {
    state.activeIndex = key
}

onMounted(() => {
    getConfig();
})

const getConfig = () => {
    getSettingApi({}).then(res => {
        if (res.code === 0) {
            state.formData = {...state.formData, ...res.data};
            for(let i in res.data){
                window.electronAPI.store.set(i, res.data[i]);
            }
        }
    });
}

const saveForm = () => {
    refForm.value?.validate(valid => {
        if (!valid) return false;

        ElMessageBox.confirm("确认提交？", '信息').then(() => {
            settingEditApi(state.formData).then(res => {
                if (res.code !== 0) return false;
                ElMessage({type: 'success', message: '保存成功'});
                getConfig();
            });
        });
    });
}
</script>